package com.horay.springclouddemo.common.http;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * 响应正文
 *
 * @author heyingcheng
 * @date 2020/2/16 19:27
 */
@Setter
@Getter
@ToString
public class ResultBody<T> {

    private static final String DEFAULT_DATA = "";

    private int code;

    private String message = DEFAULT_DATA;

    private T data;

    private static final Map<Integer, HttpStatus> HTTP_STATUS_MAP = new HashMap<>();

    static {
        for (HttpStatus httpStatus : HttpStatus.values()) {
            HTTP_STATUS_MAP.put(httpStatus.value(), httpStatus);
        }
    }

    public ResultBody() {
    }

    public ResultBody(int code) {
        this.code = code;
    }

    public ResultBody(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public ResultBody(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> ResultBody<T> ok() {
        return new ResultBody(0, HttpStatus.OK.getReasonPhrase(), DEFAULT_DATA);
    }

    public static <T> ResultBody<T> ok(T data) {
        return new ResultBody(0, HttpStatus.OK.getReasonPhrase(), data);
    }

    public static <T> ResultBody<T> custom(int code) {
        return new ResultBody(code);
    }

    public static <T> ResultBody<T> custom(int code, String message) {
        return new ResultBody(code, message, DEFAULT_DATA);
    }

    public static <T> ResultBody<T> custom(int code, String message, T data) {
        return new ResultBody(code, message, data);
    }

    public static <T> ResultBody<T> custom(HttpStatus httpStatus) {
        return new ResultBody(httpStatus.value(), httpStatus.getReasonPhrase(), DEFAULT_DATA);
    }

    public static <T> ResultBody<T> custom(HttpStatus httpStatus, T data) {
        return new ResultBody(httpStatus.value(), httpStatus.getReasonPhrase(), data);
    }

    public static HttpStatus code2HttpStatus(int code) {
        return HTTP_STATUS_MAP.getOrDefault(code, HttpStatus.NOT_FOUND);
    }

}
